import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Table, Divider, Modal, message, Popconfirm } from 'antd';
import Form from './components/SearchForm';
import { optionEnable } from './service';
import { checkInit } from '@/utils/util';
import { UmiComponentProps, BaseComponentProps } from '@/common/type';

export interface P {
  list?: {
    data: Array<any>,
    dataCnt: number
  };
  parentId: string;
  count?: any;
}

const confirm = Modal.confirm;

type Props = P & UmiComponentProps & BaseComponentProps;

@connect(({ position_xl, loading, menu }) => ({
  list: position_xl.list || {},
  dict: position_xl.dict || {},
  cond: position_xl.cond,
  buttons: menu.buttons,
  loading: loading.effects['position_xl/queryPage']
}))
class Position extends Component<Props, any> {
  constructor(props) {
    super(props);
    this.initCurrent = this.initCurrent.bind(this);
    this.showConfirm = this.showConfirm.bind(this);
    this.delConfirm = this.delConfirm.bind(this);
  }
  state = {
    current: 1
  };

  private queryData(offset = 1) {
    const { dispatch } = this.props;

    dispatch({
      type: 'position_xl/queryPage',
      payload: {
        pageNum: offset
      },
    });
  }

  initCurrent() {
    this.setState({
      current: 1
    })
  }

  showConfirm(data) { // 是否启用
    let params = {
      id: data.id
    };
    let tipMsg = message.loading('');
    return optionEnable(params).then(() => {
      tipMsg();
      message.success('操作成功', 1.5);
      this.queryData();
    }, tipMsg);
  }

  delConfirm(data) { // 删除
    let that = this;
    confirm({
      title: '删除',
      content: '是否删除？',
      onOk() {
        let params = {
          id: data.id
        };
        let tipMsg = message.loading('');
        return optionEnable(params).then(() => {
          tipMsg();
          message.success('操作成功', 1.5);
          that.queryData();
        }, tipMsg);
      },
      onCancel() { },
      okText: "确认",
      cancelText: "取消"
    });
  }

  componentDidMount() {
    const { dispatch } = this.props;
    checkInit() ? dispatch({ type: `position_xl/initCond` }) : this.queryData();
  }

  handleDelete = (id) => {
    const { dispatch } = this.props
    dispatch({ type: 'position_xl/remove', payload: id })
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond = {} } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `position_xl/updateCond`, payload: cond }).then(() => {
      this.initCurrent()
    })
  }

  render() {
    const { buttons } = this.props;
    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }
    const { data = [], dataCnt } = this.props.list;
    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      ind: index + 1 < 10 ? `0${index + 1}` : index + 1,
      id: item.id, // 主键编号
      name: item.name,  // 巡逻点名称
      statusName: item.positionLogStatusName || '待巡逻', // 状态
      nfcNo: item.nfcNo,  // nfc编号
      enable: item.enable   // 是否启用
    })) : [];

    const pagination = {
      total: dataCnt,
      showTotal: (total: number) => `共 ${total} 条`,
      current: this.state.current,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      showSizeChanger: true,
      onChange: (current: number) => {
        this.setState({ current }, () => this.queryData(current));
      },
    };
    const columns = [{
      title: '巡逻点名称',
      dataIndex: 'name',
    }, {
      title: '状态',
      dataIndex: 'statusName',
    }, {
      title: 'NFC',
      dataIndex: 'nfcNo',
    }, {
      title: '是否启用',
      dataIndex: 'enable',
      render: (text, record) => `${+record.enable === 1 ? '是' : '否'}`
    }, {
      title: '操作', key: 'x', render: (record, text, index) => {
        return (
          <div style={{ display: 'flex' }}>
            {/* <Popconfirm   okText="确定" cancelText="取消" title={`${+record.enable === 1 ? '是否起用？' : '是否停用？'}`} onConfirm={() => { this.showConfirm(record) }}>
            <span
              style={{ 'cursor': 'pointer', 'color': '#0880DF' }}>
              {+record.enable === 1 ? '停用' : '启用'}
            </span>
            </Popconfirm> */}
            <Popconfirm title="请确认是否删除?" okText="确定" cancelText="取消"  onConfirm={() => { this.handleDelete(record.id) }}>
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Link to={`/data/position/${record.id}/update`}>编辑</Link>
          </div>
        )
      }
    }];
    return (
      <div>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} />
        <Table
          columns={[{
            title: '序号',
            dataIndex: 'ind',
          }, ...columns]}
          pagination={pagination}
          dataSource={ans}
          bordered
          loading={this.props.loading}
        />
      </div>
    );
  }
}

export default Position;
